class User < ActiveRecord::Base
  include ActiveModel::Validations

  class UniquenessEnterpriseValidator < ActiveModel::EachValidator
    def validate_each(record, attribute, value)
      record.errors[attribute] << "已注册" if value.nil?
    end
  end
  
  validates :enterprise_id,
    :uniqueness_enterprise => true
  validates :full_name,
    :mobile,
    :email,
    :presence => true  
  validates :email, 
    :format => {
      :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
    }
  validates :mobile,
    :uniqueness  => {
      :scope =>  :enterprise_id    
    }
  validates :email,
    :uniqueness  => {
      :scope =>  :enterprise_id    
    }
  validates :encrypted_password,
    :confirmation => true        
    
  belongs_to :enterprise
  has_and_belongs_to_many :groups, :uniq => true

  scope :active, lambda { where(:status => 'active') }
  scope :workmates, lambda { where(:enterprise_id => User.current.enterprise) }
  
  before_create do |user|
    user.pk = ActiveSupport::SecureRandom.hex(128)
  end
  
  before_save do |user|
    user.encode_password! if user.encrypted_password_changed?
  end

  def is_admin?
    enterprise.admin == self
  end
  
  def self.current
    Thread.current[:current_user_id] ? find(Thread.current[:current_user_id]) : nil
  end
  
  def self.current_id 
    Thread.current[:current_user_id]
  end
  
  # 当前登录人？
  def current?
    id == User.current.try(:id)
  end
  
  def self.has_loggined?
    current
  end
    
  def self.authenticate(args = {})    
    find_by_enterprise_name_and_mobile_encrypted_password(args)
  end
  
  def self.find_by_enterprise_name_and_mobile_encrypted_password(args = {})
    where(
      'enterprises.name = :enterprise_name and users.mobile = :mobile and users.encrypted_password = :encrypted_password ', 
      args.merge( :encrypted_password => Base64.encode64(args[:password]).chop)
    ).includes(:enterprise).first
  end
  
  def password
    Base64.decode64(encrypted_password) if encrypted_password?
  end
  
    # 安全key存储在cookies
  def security_key_in_cookies
    Digest::SHA1.hexdigest(id.to_s + pk)
  end

  def check_security_key_in_cookies(sk)
    security_key_in_cookies == sk
  end
  
  def reset_password!
    self.encrypted_password = '1234'
    save(:validate => false)
  end
  
  # 加密密码
  def encode_password!
    self.encrypted_password = Base64.encode64(encrypted_password).chop
  end
  
  def status
    ActiveSupport::StringInquirer.new(self[:status])
  end

  def feed_view_type
    ActiveSupport::StringInquirer.new(self[:feed_view_type])
  end
  
  def locked!
    status! 'locked'
  end
  
  def active!
    status! 'active'
  end
  
  def status!(new_status)
    self.status = new_status
    save(:validate => false)
  end

  def nick_name
    id == User.current_id ?  '我' : full_name
  end
    
end
